package admin

import (
	"baokaobang/datasourse"
	"baokaobang/models"
	"baokaobang/utils"
	"encoding/json"
	"fmt"
	"github.com/kataras/iris/v12"
	"github.com/kataras/iris/v12/mvc"
	"time"
)

type University struct {
	Ctx iris.Context
}

type UniversityCreate struct {
	Id           string  `json:"id"`
	ProvinceId   int64   `json:"provinceId"`
	CityId       int64   `json:"cityId"`
	DistrictId   int64   `json:"districtId"`
	Name         string  `json:"name"`
	MType        int     `json:"type"`
	Nature       int     `json:"nature"`
	LogoPic      string  `json:"logoPic"`
	Code         string  `json:"code"`
	Introduction string  `json:"introduction"`
	Telephone    string  `json:"telephone"`
	Address      string  `json:"address"`
	Website      string  `json:"website"`
	Labels       []int64 `json:"labels"`
}

type UniversityListParam struct {
	ProvinceId int64  `json:"provinceId"`
	CityId     int64  `json:"cityId"`
	DistrictId int64  `json:"districtId"`
	MType      int    `json:"type"`
	Nature     int    `json:"nature"`
	Name       string `json:"name"`
	PerPage    int    `json:"perPage"`
	CurPage    int    `json:"curPage"`
}

type UniversityListItem struct {
	Id          int64     `json:"universityId"`
	Name        string    `json:"universityName"`
	MType       int       `json:"universityType"`
	Nature      int       `json:"universityNature"`
	Code        string    `json:"universityCode"`
	Created     time.Time `json:"-"`
	CreatedShow string    `xorm:"-" json:"universityCreated"`
	TypeShow    string    `xorm:"-" json:"universityTypeShow"`
	NatureShow  string    `xorm:"-" json:"universityNatureShow"`
}

type UniversityItem struct {
	Id   int64  `json:"universityId"`
	Name string `json:"universityName"`
}

func (c *University) OptionsAll() mvc.Response {
	return mvc.Response{
		Code: 204,
	}
}

func (c *University) PostAll() interface{} {
	db, err := datasourse.NewMasterOrm()
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("无法连接数据库:%s", err.Error()), "")
	}

	universityList := make([]UniversityItem, 0)
	err = db.Table(new(models.University)).Find(&universityList)
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("无法获取所有大学列表:%s", err.Error()), "")
	}

	return utils.CommonRes(20000, "成功获取所有大学列表", universityList)
}

func (c *University) OptionsCreate() mvc.Response {
	return mvc.Response{
		Code: 204,
	}
}

func (c *University) PostCreate() interface{} {
	universityCreate := UniversityCreate{}
	content, err := c.Ctx.GetBody()
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("接收请求参数出错:%s", err.Error()), "")
	}
	err = json.Unmarshal(content, &universityCreate)
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("解析请求参数出错:%s", err.Error()), "")
	}

	if universityCreate.ProvinceId <= 0 {
		return utils.CommonRes(1000, "请选择省", "")
	}
	if universityCreate.CityId <= 0 {
		return utils.CommonRes(1000, "请选择市", "")
	}
	if len(universityCreate.Name) <= 0 {
		return utils.CommonRes(1000, "请输入大学名称", "")
	}
	if len(universityCreate.LogoPic) <= 0 {
		return utils.CommonRes(1000, "请上传大学logo", "")
	}
	if len(universityCreate.Code) <= 0 {
		return utils.CommonRes(1000, "请输入大学代码", "")
	}

	db, err := datasourse.NewMasterOrm()
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("无法连接数据库%s", err.Error()), "")
	}

	sess := db.NewSession()
	defer sess.Close()
	err = sess.Begin()
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("事务开启失败：%s", err.Error()), "")
	}

	university := new(models.University)
	university.ProvinceId = universityCreate.ProvinceId
	university.CityId = universityCreate.CityId
	university.DistrictId = universityCreate.DistrictId
	university.Name = universityCreate.Name
	university.MType = universityCreate.MType
	university.Nature = universityCreate.Nature
	university.Code = universityCreate.Code
	university.LogoPic = universityCreate.LogoPic
	university.Introduction = universityCreate.Introduction
	university.Telephone = universityCreate.Telephone
	university.Address = universityCreate.Address
	university.Website = universityCreate.Website

	_, err = sess.InsertOne(university)
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("操作失败：%s", err.Error()), "")
	}

	for _, labelId := range universityCreate.Labels {
		universityLabel := new(models.UniversityLabel)
		universityLabel.UniversityId = university.Id
		universityLabel.LabelId = labelId
		_, err = sess.InsertOne(universityLabel)
		if err != nil {
			return utils.CommonRes(1000, fmt.Sprintf("操作失败：%s", err.Error()), "")
		}
	}

	err = sess.Commit()
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("操作失败：%s", err.Error()), "")
	}

	return utils.CommonRes(20000, "操作成功", "")
}

func (c *University) OptionsEdit() mvc.Response {
	return mvc.Response{
		Code: 204,
	}
}

func (c *University) PostEdit() interface{} {
	universityCreate := UniversityCreate{}
	content, err := c.Ctx.GetBody()
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("解析请求参数出错:%s", err.Error()), "")
	}
	err = json.Unmarshal(content, &universityCreate)
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("解析参数出错:%s", err.Error()), "")
	}

	if len(universityCreate.Id) <= 0 {
		return utils.CommonRes(1000, "请提供大学id", "")
	}
	if universityCreate.ProvinceId <= 0 {
		return utils.CommonRes(1000, "请选择省", "")
	}
	if universityCreate.CityId <= 0 {
		return utils.CommonRes(1000, "请选择市", "")
	}
	if len(universityCreate.Name) <= 0 {
		return utils.CommonRes(1000, "请输入大学名称", "")
	}
	if len(universityCreate.LogoPic) <= 0 {
		return utils.CommonRes(1000, "请上传大学logo", "")
	}
	if len(universityCreate.Code) <= 0 {
		return utils.CommonRes(1000, "请输入大学代码", "")
	}

	db, err := datasourse.NewMasterOrm()
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("无法连接数据库:%s", err.Error()), "")
	}

	sess := db.NewSession()
	defer sess.Close()
	err = sess.Begin()
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("事务开启失败：%s", err.Error()), "")
	}

	updateData := map[string]interface{}{
		"province_id":  universityCreate.ProvinceId,
		"city_id":      universityCreate.CityId,
		"district_id":  universityCreate.DistrictId,
		"name":         universityCreate.Name,
		"m_type":       universityCreate.MType,
		"nature":       universityCreate.Nature,
		"logo_pic":     universityCreate.LogoPic,
		"code":         universityCreate.Code,
		"introduction": universityCreate.Introduction,
		"telephone":    universityCreate.Telephone,
		"address":      universityCreate.Address,
		"Website":      universityCreate.Website,
	}
	_, err = sess.Table(new(models.University)).ID(universityCreate.Id).Update(updateData)
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("大学信息更新失败：%s", err.Error()), "")
	}

	universityLabelList := make([]models.UniversityLabel, 0)
	sess.Where("university_id = ?", universityCreate.Id).Find(&universityLabelList)
	for _, universityLabel := range universityLabelList {
		_, err = sess.ID(universityLabel.Id).Delete(universityLabel)
		if err != nil {
			return utils.CommonRes(1000, fmt.Sprintf("大学旧标签删除失败：%s", err.Error()), "")
		}
	}

	for _, labelId := range universityCreate.Labels {
		newUniversityLabel := new(models.UniversityLabel)
		newUniversityLabel.UniversityId = utils.Atoi64(universityCreate.Id)
		newUniversityLabel.LabelId = labelId
		_, err = sess.InsertOne(newUniversityLabel)
		if err != nil {
			return utils.CommonRes(1000, fmt.Sprintf("大学新标签插入失败：%s", err.Error()), "")
		}
	}

	err = sess.Commit()
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("操作失败：%s", err.Error()), "")
	}

	return utils.CommonRes(20000, "操作成功", "")
}

func (c *University) OptionsList() mvc.Response {
	return mvc.Response{
		Code: 204,
	}
}

func (c *University) PostList() interface{} {
	universityListParam := UniversityListParam{}
	content, err := c.Ctx.GetBody()
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("解析请求参数出错:%s", err.Error()), "")
	}
	err = json.Unmarshal(content, &universityListParam)
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("解析参数出错:%s", err.Error()), "")
	}

	db, err := datasourse.NewMasterOrm()
	if err != nil {
		return utils.CommonRes(1000, "无法连接服务器", "")
	}

	start := (universityListParam.CurPage - 1) * universityListParam.PerPage
	universityList := make([]UniversityListItem, 0)
	sess := db.Table(new(models.University)).Limit(universityListParam.PerPage, start)
	if universityListParam.ProvinceId > 0 {
		sess = sess.Where("province_id = ?", universityListParam.ProvinceId)
	}
	if universityListParam.CityId > 0 {
		sess = sess.Where("city_id = ?", universityListParam.CityId)
	}
	if universityListParam.DistrictId > 0 {
		sess = sess.Where("district_id = ?", universityListParam.DistrictId)
	}
	if universityListParam.MType > 0 {
		sess = sess.Where("m_type = ?", universityListParam.MType)
	}
	if universityListParam.Nature > 0 {
		sess = sess.Where("nature = ?", universityListParam.Nature)
	}
	if len(universityListParam.Name) > 0 {
		sess = sess.Where("name like ?", fmt.Sprintf("%%%s%%", universityListParam.Name))
	}
	err = sess.Find(&universityList)
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("无法获取大学列表:%s", err.Error()), "")
	}

	countSess := db.Where("id > ?", 0)
	if universityListParam.ProvinceId > 0 {
		countSess = countSess.Where("province_id = ?", universityListParam.ProvinceId)
	}
	if universityListParam.CityId > 0 {
		countSess = countSess.Where("city_id = ?", universityListParam.CityId)
	}
	if universityListParam.DistrictId > 0 {
		countSess = countSess.Where("district_id = ?", universityListParam.DistrictId)
	}
	if universityListParam.MType > 0 {
		countSess = countSess.Where("m_type = ?", universityListParam.MType)
	}
	if universityListParam.Nature > 0 {
		countSess = countSess.Where("nature = ?", universityListParam.Nature)
	}
	if len(universityListParam.Name) > 0 {
		countSess = countSess.Where("name like ?", fmt.Sprintf("%%%s%%", universityListParam.Name))
	}
	total, err := countSess.Count(new(models.University))
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("无法获取大学列表:%s", err.Error()), "")
	}

	for i, item := range universityList {
		universityList[i].TypeShow = models.UniversityType[item.MType]
		universityList[i].NatureShow = models.UniversityNature[item.Nature]
	}

	data := map[string]interface{}{
		"total": total,
		"list":  universityList,
	}

	return utils.CommonRes(20000, "成功获取大学列表", data)
}

func (c *University) OptionsDetail() mvc.Response {
	return mvc.Response{
		Code: 204,
	}
}

func (c *University) PostDetail() interface{} {
	editParam := utils.EditParam{}
	content, err := c.Ctx.GetBody()
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("接收请求参数出错:%s", err.Error()), "")
	}
	err = json.Unmarshal(content, &editParam)
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("解析请求参数出错:%s", err.Error()), "")
	}

	if len(editParam.Id) <= 0 {
		return utils.CommonRes(1000, "请提供大学id", "")
	}

	db, err := datasourse.NewMasterOrm()
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("无法连接数据库：%s", err.Error()), "")
	}

	university := new(models.University)
	ok, err := db.ID(editParam.Id).Get(university)
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("信息获取失败：%s", err.Error()), "")
	}
	if !ok {
		return utils.CommonRes(1000, "信息获取失败", "")
	}

	universityLabelList := make([]models.UniversityLabel, 0)
	err = db.Where("university_id = ? ", editParam.Id).Find(&universityLabelList)
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("信息获取失败：%s", err.Error()), "")
	}
	university.Labels = universityLabelList

	return utils.CommonRes(20000, "信息获取成功", university)
}
